import sys
import os

def convert(text):
    return text.replace("&", "&amp;") \
               .replace("<", '&lt;')  \
               .replace(">", "&gt;")  \
               .replace("\"", "&quot;")

def getCodeViewDirective(extension):
    if extension in [".py", ".pyw"]:
        return "@@language=python\n"
    if extension in [".h", ".hpp", ".cpp", ".cxx", ".c"]:
        return "@@language=c++\n"
    if extension in [".pas"]:
        return "@@language=pascal\n"
    if extension in [".php"]:
        return "@@language=php\n"
    if extension in [".js"]:
        return "@@language=javascript\n"
    if extension in [".bas"]:
        return "@@language=basic\n"
    if extension in [".cs"]:
        return "@@language=c#\n"
    if extension in [".rb"]:
        return "@@language=ruby\n"
    if extension in [".pl"]:
        return "@@language=perl\n"
    if extension in [".java"]:
        return "@@language=java\n"
    if extension in [".groovy"]:
        return "@@language=groovy\n"
    if extension in [".d"]:
        return "@@language=d\n"
    if extension in [".scala"]:
        return "@@language=scala\n"
    if extension in [".cmd", ".bat"]:
        return "@@language=batch\n"
    return ""

def createHTML(fileName):
    oldstdout  = sys.stdout
    sys.stdout = open(fileName + ".html", "w")

    codeViewDirective = getCodeViewDirective(os.path.splitext(fileName)[1])

    print("""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">""")
    print("<html>")
    print("    <head>")
    print("        <title>%s</title>" % fileName)
    print("""
        <script type="text/javascript" src="../src/ClassTools.js"></script>
        <script type="text/javascript" src="../src/StringTools.js"></script>
        <script type="text/javascript" src="../src/Keywords.js"></script>
        <script type="text/javascript" src="../src/Comments.js"></script>
        <script type="text/javascript" src="../src/Stylesheets.js"></script>
        <script type="text/javascript" src="../src/DefaultScanner.js"></script>
        <script type="text/javascript" src="../src/CodeView.js"></script>
          """)
    print("    </head>")
    print("    <body onload=\"highlight('pre')\">")
    print("        <pre>%s%s</pre>" % (codeViewDirective, convert(open(fileName).read())))
    print("    </body>")
    print("</html>")

    sys.stdout.close()
    sys.stdout = oldstdout

def main():
    for entry in os.listdir("."):
        root, ext = os.path.splitext(entry)
        if ext in [".py", ".cxx", ".c", ".pas", ".js", ".java", ".php",
                   ".cs", ".bas", ".rb", ".pl", ".groovy", ".d", ".scala",
                   ".cmd", ".bat" ]:
            createHTML(entry)

if __name__ == "__main__":
    main()
